<?php

namespace App\Http\Controllers;

use App\Models\Article;
use App\Models\User;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Session;
use Laravel\Socialite\Facades\Socialite;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\URL;

class LoginController extends BaseController
{

    public function redirectToProvider(Request $request,$service)
    {
        Session::put('backUrl',URL::previous());
        return Socialite::driver($service)->redirect();
    }

    public function handleProviderCallback(Request $request,$service)
    {
        $u = Socialite::driver($service)->user();
        /*dd($u->nickname);*/
        //dd($u->user['gender']);
        $user=User::where('openId',$u->id)->first();
        if($user==null){
            $user=new User;
            $user->name=$u->nickname;
            $user->token=$u->token;
            $user->avatar=$u->avatar;
            $user->openId=$u->id;
            $user->user=json_encode($u->user);
            if($service=='qq'){
                $user->type=0;
                if($u->user['gender']=='男'){
                    $user->gender='男';
                }elseif ($u->user['gender']=='女'){
                    $user->gender='女';
                }
            }else{
                $user->type=1;
                if($u->user['gender']=='m'){
                    $user->gender='男';
                }elseif ($u->user['gender']=='f'){
                    $user->gender='女';
                }
            }

            $user->save();
        }
        session(['user'=>$user]);
        Session::save();
        $backUrl = Session::get('backUrl');
        Session::forget('backUrl');
        return redirect($backUrl);
    }

    public function loginout()
    {
        session(['user'=>null]);
        return redirect(URL::previous());
    }

    public function testSession()
    {
        dd(session('user'));
    }
}
